package com.example.com.transcribeeditpublish.popuWindow;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.com.transcribeeditpublish.R;
import com.example.com.transcribeeditpublish.TCVideoEditerWrapper;
import com.example.com.transcribeeditpublish.activity.VideoEditActivity;
import com.example.com.transcribeeditpublish.utils.DialogUtil;
import com.example.com.transcribeeditpublish.utils.TCBGMInfo;
import com.example.com.transcribeeditpublish.utils.TCMusicManager;
import com.tencent.ugc.TXVideoEditConstants;
import com.tencent.ugc.TXVideoEditer;

import java.util.ArrayList;

import me.goldze.mvvmhabit.utils.KLog;

public class SelectBbmPpWindow extends PopupWindow {
    private final VideoEditActivity mVideoEditActivity;
    private final BGMCallBack bgmCallBack;
    private RecyclerView recyclerView;
    private final View mMenuView;
    private TextView empty;
    private TextView currentMusic;
    private TXVideoEditer mEditer;
    private LinearLayout mRlLoading;
    private ArrayList<TCBGMInfo> mMusicList;
    private int mCurrentMusic = -1;

    public SelectBbmPpWindow(VideoEditActivity videoEditActivity, BGMCallBack bgmCallBack) {
        this.mVideoEditActivity = videoEditActivity;
        this.bgmCallBack = bgmCallBack;
        mMenuView = LayoutInflater.from(mVideoEditActivity).inflate(R.layout.popuwindow_music, null, false);
        getEditer();
        initView();

        setRecyclerView(mVideoEditActivity);
        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //适配虚拟键
        this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
        this.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(RelativeLayout.LayoutParams.WRAP_CONTENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x00000000); //android:background="#30000000"
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
    }

    private void initView() {
        recyclerView = (RecyclerView) mMenuView.findViewById(R.id.m_rv);
        empty = (TextView) mMenuView.findViewById(R.id.m_empty);
        currentMusic = (TextView) mMenuView.findViewById(R.id.current_music);
        mRlLoading = (LinearLayout) mMenuView.findViewById(R.id.chose_rl_loading_music);
        mMenuView.findViewById(R.id.cancle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isSuccess = onSetBGMInfo(null);
                if (isSuccess) {
                    currentMusic.setText("当前音乐: ");
                    int lastIndex = mCurrentMusic;
                    mCurrentMusic = -1;
                    recyclerView.getAdapter().notifyItemChanged(lastIndex);
                }
            }
        });
    }

    private void setRecyclerView(Context context) {
        recyclerView.setLayoutManager(new LinearLayoutManager(context));

        mMusicList = new ArrayList<>();
        recyclerView.setAdapter(new MAdapter());
        mRlLoading.setVisibility(View.VISIBLE);
        mMenuView.postDelayed(new Runnable() {
            @Override
            public void run() {
                loadMusicAndSetAdapter();
            }
        }, 500);
    }

    /**
     * 开启子线程获取音频列表
     */
    private void loadMusicAndSetAdapter() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                mMusicList.clear();
                mMusicList.addAll(TCMusicManager.getInstance(mVideoEditActivity).getAllMusic());
                //切换到主线程
                mVideoEditActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        KLog.e("mRlLoading", "mRlLoading");
                        mRlLoading.setVisibility(View.GONE);
                        if (mMusicList != null && mMusicList.size() > 0) {
                            recyclerView.getAdapter().notifyDataSetChanged();
                        } else {
                            empty.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }
        }).start();
    }

    private void getEditer() {
        mEditer = TCVideoEditerWrapper.getInstance().getEditer();
    }

    /**
     * BGM信息配置
     *
     * @param info 为null不设置BGM
     */
    private boolean onSetBGMInfo(TCBGMInfo info) {
        if (info == null) {
            mEditer.setBGM(null); //不设置BGM
            if (bgmCallBack != null)
                bgmCallBack.select(null);
            return true;
        } else {
            String bgmPath = info.getPath();
            Log.e("BGM", bgmPath);
            if (!TextUtils.isEmpty(bgmPath)) {
                int result = mEditer.setBGM(bgmPath);
                if (result != 0) {
                    if (result == TXVideoEditConstants.ERR_UNSUPPORT_VIDEO_FORMAT) {
                        DialogUtil.showDialog(mVideoEditActivity, "添加背景音乐失败", "视频本身无声音目前不支持添加背景音乐", null);
                    } else {
                        DialogUtil.showDialog(mVideoEditActivity, "视频编辑失败", "背景音仅支持MP3格式或M4A音频", null);
                    }
                }
                mEditer.setBGMStartTime(10, info.getDuration());
                mEditer.setBGMLoop(true);//循环
                // mEditer.setBGMFadeInOutDuration(3000, 3000);//淡入淡出
                mEditer.setBGMVolume(0.5f);
                mEditer.setVideoVolume(0.5f);
                if (bgmCallBack != null)
                    bgmCallBack.select(info);
                return result == 0;//设置成功
            }
        }
        return false;
    }

    public void show(VideoEditActivity videoEditActivity) {
        this.showAtLocation(videoEditActivity.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
    }

    private class MAdapter extends RecyclerView.Adapter<LinearMusicViewHolder> {
        @Override
        public LinearMusicViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new LinearMusicViewHolder(View.inflate(parent.getContext(), R.layout.item_editer_bgm, null));
        }

        @Override
        public void onBindViewHolder(LinearMusicViewHolder holder, final int position) {
            TCBGMInfo info = mMusicList.get(position);
            holder.tvName.setText(info.getSongName() + "  —  " + info.getSingerName());
            holder.tvDuration.setText(info.getFormatDuration());
            if (mCurrentMusic == position) {
                holder.tvName.setTextColor(mVideoEditActivity.getResources().getColor(R.color.red_f0));
                holder.tvDuration.setTextColor(mVideoEditActivity.getResources().getColor(R.color.red_f0));
            } else {
                holder.tvName.setTextColor(mVideoEditActivity.getResources().getColor(R.color.white));
                holder.tvDuration.setTextColor(mVideoEditActivity.getResources().getColor(R.color.white));
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setBGM(position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mMusicList.size();
        }
    }

    private void setBGM(int position) {
        TCBGMInfo bgmInfo = mMusicList.get(position);
        if (bgmInfo == null) {
            return;
        }
        boolean isSuccess = onSetBGMInfo(bgmInfo);
        int lastIndex = mCurrentMusic;
        if (isSuccess) {
            mCurrentMusic = position;
            recyclerView.getAdapter().notifyItemChanged(lastIndex);
            recyclerView.getAdapter().notifyItemChanged(position);
            currentMusic.setText("当前音乐: " + bgmInfo.getSongName());
        } else {
            mCurrentMusic = -1;
            recyclerView.getAdapter().notifyItemChanged(lastIndex);
            currentMusic.setText("当前音乐: ");
        }
    }

    private class LinearMusicViewHolder extends RecyclerView.ViewHolder {
        private final TextView tvDuration;
        private final TextView tvName;

        public LinearMusicViewHolder(View inflate) {
            super(inflate);
            tvName = (TextView) itemView.findViewById(R.id.bgm_tv_name);
            tvDuration = (TextView) itemView.findViewById(R.id.bgm_tv_duration);
        }
    }

    public interface BGMCallBack {
        void select(TCBGMInfo bgmPath);
    }
}
